import crypto from 'crypto'
import { APPID, APPSECRET } from './appid'

//#region sign
function genSignature(params, secret) {
  let entries = Object.entries(params).sort()
  const querystring = entries
    .map(([key, value]) => {
      return [key, encodeURIComponent(value)]
    })
    .map(([key, value]) => {
      return `${key}=${value}`
    })
    .join('&')

  const hmac = crypto.createHmac('sha1', secret)
  hmac.update(querystring)
  const signature = hmac.digest('base64')
  return signature
}

// type HTTPMethod = 'POST' | 'GET' | 'PUT' | 'DELETE'

export default function sign(
  method,
  path,
  nonce,
  timestamp
) {
  const appId = APPID
  const signature = genSignature(
    {
      appId,
      method,
      nonce,
      path,
      timestamp,
    },
    APPSECRET
  )
  return signature
}
//#endregion sign